/*
 */

package com.railway.news.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.ModelDriven;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.railway.common.base.*;
import com.railway.common.util.*;

import cn.org.rapid_framework.util.*;
import cn.org.rapid_framework.web.util.*;
import cn.org.rapid_framework.page.*;
import cn.org.rapid_framework.page.impl.*;

import com.railway.news.model.*;
import com.railway.news.dao.*;
import com.railway.news.service.*;
import com.railway.news.vo.query.*;

/**
 * @author jiangcheng
 * @version 1.0
 * @since 1.0
 */

public class MenuAction extends BaseStruts2Action implements Preparable,
		ModelDriven {
	// 默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = null;

	// forward paths
	protected static final String QUERY_JSP = "/admin/news/menu/query.jsp";
	protected static final String TOP_LIST = "/admin/news/menu/toplist.jsp";
	protected static final String LIST_JSP = "/admin/news/menu/list.jsp";
	protected static final String CREATE_JSP = "/admin/news/menu/create.jsp";
	protected static final String EDIT_JSP = "/admin/news/menu/edit.jsp";
	protected static final String SHOW_JSP = "/admin/news/menu/show.jsp";
	// redirect paths,startWith: !
	protected static final String LIST_ACTION = "!/news/Menu/list.do";

	private IMenuManager menuManager;

	private Menu menu;
	java.lang.String id = null;
	private String[] items;
	private String param;

	public void setParam(String param) {
		this.param = param;
	}

	public void prepare() throws Exception {
		if (isNullOrEmptyString(id)) {
			menu = new Menu();
		} else {
			menu = (Menu) menuManager.getById(id);
		}
	}

	/** 增加setXXXX()方法,spring就可以通过autowire自动设置对象属性,注意大小写 */
	public void setMenuManager(IMenuManager manager) {
		this.menuManager = manager;
	}

	public Object getModel() {
		return menu;
	}

	public void setId(java.lang.String val) {
		this.id = val;
	}

	public void setItems(String[] items) {
		this.items = items;
	}

	/** 执行搜索 */
	public String list() {
		return LIST_JSP;
	}

	public String listAjax() {
		MenuQuery query = newQuery(MenuQuery.class, DEFAULT_SORT_COLUMNS);
		Page page = menuManager.findPage(query);
		Map map = new HashMap();
		map.put("total", page.getTotalCount());
		map.put("rows", page.getResult());
		return writeAjaxResponse(Json.toJson(map));
	}

	public String topManager() {

		return TOP_LIST;
	}

	public String topList() {
		MenuQuery query = newQuery(MenuQuery.class, DEFAULT_SORT_COLUMNS);
		query.setSortColumns("priors");
		List<Menu> list = menuManager.findPageList(query);
		Map map = new ConcurrentHashMap();
		// 页顶标题
		List<Menu> topTitle = new ArrayList();
		// 菜单
		List<Menu> menus = new ArrayList();
		// 左侧标题
		List<Menu> leftTitle = new ArrayList();
		// 友情链接
		List<Menu> friendLink = new ArrayList();
		// 友情链接
		List<Menu> friendLink1 = new ArrayList();
		// 友情链接
		List<Menu> friendLink2 = new ArrayList();
		Menu safe1 = new Menu();
		Menu safe2 = new Menu();
		Menu safe3 = new Menu();
		Menu weather = new Menu();
		Menu title = new Menu();

		if (list != null) {
			for (int i = 0; i < list.size(); i++) {
				Menu menu = (Menu) list.get(i);
				if (menu.getLocations() == null) {
				} else if (menu.getLocations().equals("topTitle")) {
					topTitle.add(menu);
				} else if (menu.getLocations().equals("menus")) {
					menus.add(menu);
				} else if (menu.getLocations().equals("leftTitle")) {
					leftTitle.add(menu);
				} else if (menu.getLocations().equals("friendLink")) {
					friendLink.add(menu);
				} else if (menu.getLocations().equals("friendLink1")) {
					friendLink1.add(menu);
				}
				 else if (menu.getLocations().equals("friendLink2")) {
						friendLink2.add(menu);
					}
				else if (menu.getLocations().equals("safe1")) {
					safe1 = menu;
				} else if (menu.getLocations().equals("safe2")) {
					safe2 = menu;
				} else if (menu.getLocations().equals("safe3")) {
					safe3 = menu;
				} else if (menu.getLocations().equals("weather")) {
					weather = menu;
				} else if (menu.getLocations().equals("title")) {
					title = menu;
				}
			}
		}

		// 递归整理菜单
		menus = StaticMap.getAllChildrenByid(menus);
		// 友情连接
		friendLink = StaticMap.getAllChildrenByid(friendLink);

		map.put("weather", weather);
		map.put("safe1", safe1);
		map.put("safe2", safe2);
		map.put("safe3", safe3);
		map.put("title", title);
		map.put("topTitle", topTitle);
		map.put("menus", menus);
		map.put("leftTitle", leftTitle);
		map.put("friendLink", friendLink);
		map.put("friendLink1", friendLink1);
		map.put("friendLink2", friendLink2);
		
		StringBuffer sb = new StringBuffer();
		sb.append("{");
		sb.append("\"weather\":");
		sb.append(Json.toJson(weather));
		sb.append(",");
		sb.append("\"safe1\":");
		sb.append(Json.toJson(safe1));
		sb.append(",");
		sb.append("\"safe2\":");
		sb.append(Json.toJson(safe2));
		sb.append(",");
		sb.append("\"safe3\":");
		sb.append(Json.toJson(safe3));
		sb.append(",");
		sb.append("\"title\":");
		sb.append(Json.toJson(title));
		sb.append(",");

		sb.append("\"topTitle\":");
		sb.append(Json.toJson(topTitle));
		sb.append(",");

		sb.append("\"menus\":");
		if (menus != null) {

			sb.append("[");
			for (int i = 0; i < menus.size(); i++) {
				Menu menu = menus.get(i);
				sb.append(Json.toJson(menu));
				if (i < menus.size() - 1) {
					sb.append(",");
				}
			}
			sb.append("]");
		} else {
			sb.append(Json.toJson(menus));
		}

		sb.append(",");

		sb.append("\"leftTitle\":");
		sb.append(Json.toJson(leftTitle));
		sb.append(",");

		sb.append("\"friendLink\":");

		if (friendLink != null) {
			sb.append("[");
			for (int i = 0; i < friendLink.size(); i++) {
				Menu menu = friendLink.get(i);
				if (menu.getChildrenMenu() != null) {
					sb.append("{");
					sb.append("\"priors\":");
					sb.append(menu.getPriors() + ",");
					sb.append("\"urls\":");
					sb.append("\"" + StaticMethod.null2String(menu.getUrls())
							+ "\",");
					sb.append("\"parenId\":");
					sb.append("\"" + StaticMethod.null2String(menu.getParenId())
							+ "\",");
					sb.append("\"id\":");
					sb.append("\"" + StaticMethod.null2String(menu.getId())
							+ "\",");
					sb.append("\"names\":");
					sb.append("\"" + StaticMethod.null2String(menu.getNames())
							+ "\",");
					sb.append("\"childrenMenu\":");
					sb.append("[");
					List<Menu> tempList = menu.getChildrenMenu();
 
					for (int j = 0; j < tempList.size(); j++) {
						Menu tempMenu = tempList.get(j);
						sb.append("{");
						sb.append("\"priors\":");
						sb.append(tempMenu.getPriors() + ",");
						sb.append("\"urls\":");
						sb.append("\""
								+ StaticMethod.null2String(tempMenu.getUrls())
								+ "\",");
						sb.append("\"parenId\":");
						sb.append("\"" + StaticMethod.null2String(tempMenu.getParenId())
								+ "\",");
						sb.append("\"id\":");
						sb.append("\""
								+ StaticMethod.null2String(tempMenu.getId())
								+ "\",");
						sb.append("\"names\":");
						sb.append("\""
								+ StaticMethod.null2String(tempMenu.getNames())
								+ "\",");
						sb.append("\"childrenMenu\":");
						if (tempMenu.getChildrenMenu() != null) {
							sb.append(Json.toJson(tempMenu.getChildrenMenu()));
						} else {
							sb.append("null");
						}
						sb.append("}");
						if(j<tempList.size()-1){
                          sb.append(",");
						}

					}
					sb.append("]");
					sb.append("}");
				} else {
					sb.append(Json.toJson(menu));
				}
				if (i < friendLink.size() - 1) {
					sb.append(",");
				}
			}
			sb.append("]");
		} else {
			sb.append(Json.toJson(friendLink));
		}
		sb.append(",");

		sb.append("\"friendLink1\":");
		if (friendLink1 != null) {
			sb.append("[");
			for (int i = 0; i < friendLink1.size(); i++) {
				Menu menu = friendLink1.get(i);
				if (menu.getChildrenMenu() != null) {
					sb.append("{");
					sb.append("\"priors\":");
					sb.append(menu.getPriors() + ",");
					sb.append("\"urls\":");
					sb.append("\"" + StaticMethod.null2String(menu.getUrls())
							+ "\",");
					sb.append("\"parenId\":");
					sb.append("\"" + StaticMethod.null2String(menu.getParenId())
							+ "\",");
					sb.append("\"id\":");
					sb.append("\"" + StaticMethod.null2String(menu.getId())
							+ "\",");
					sb.append("\"names\":");
					sb.append("\"" + StaticMethod.null2String(menu.getNames())
							+ "\"");
					sb.append("}");
				} else {
					sb.append(Json.toJson(menu));
				}
				if (i < friendLink1.size() - 1) {
					sb.append(",");
				}
			}
			sb.append("]");
		} else {
			sb.append(Json.toJson(friendLink1));
		}
		sb.append(",");

		sb.append("\"friendLink2\":");
		if (friendLink2 != null) {
			sb.append("[");
			for (int i = 0; i < friendLink2.size(); i++) {
				Menu menu = friendLink2.get(i);
				if (menu.getChildrenMenu() != null) {
					sb.append("{");
					sb.append("\"priors\":");
					sb.append(menu.getPriors() + ",");
					sb.append("\"urls\":");
					sb.append("\"" + StaticMethod.null2String(menu.getUrls())
							+ "\",");
					sb.append("\"parenId\":");
					sb.append("\"" + StaticMethod.null2String(menu.getParenId())
							+ "\",");
					sb.append("\"id\":");
					sb.append("\"" + StaticMethod.null2String(menu.getId())
							+ "\",");
					sb.append("\"names\":");
					sb.append("\"" + StaticMethod.null2String(menu.getNames())
							+ "\"");
					sb.append("}");
				} else {
					sb.append(Json.toJson(menu));
				}
				if (i < friendLink2.size() - 1) {
					sb.append(",");
				}
			}
			sb.append("]");
		} else {
			sb.append(Json.toJson(friendLink2));
		}
		sb.append("}");
		return writeAjaxResponse(sb.toString());
	}

	/** 查看对象 */
	public String show() {
		return SHOW_JSP;
	}

	/** 查看对象 */
	public String showAjax() {
		return writeAjaxResponse(Json.toJson(menu));
	}

	/** 进入新增页面 */
	public String create() {
		return CREATE_JSP;
	}

	/** 保存新增对象 */
	public String save() {
		try {

			menuManager.save(menu);
		} catch (Exception e) {
			System.out.print(e);
		}
		return LIST_ACTION;
	}

	/** 保存新增对象 */
	public String saveAjax() {
		String current_user_id = (String) this.getRequest().getSession()
				.getAttribute("userId");
		String result = "false";

		// if (current_user_id != null && !current_user_id.equals("")) {
		try {
			String type = getRequest().getParameter("param");

			if (type != null && type.equals("weather")) {

				// 天气预报保存
				menu.setLocations("weather");
				menu.setUrls(getRequest().getParameter("imgUrl"));
				menu.setId(getRequest().getParameter("weatherid"));
				String weathername[] = this.getRequest().getParameterValues(
						"weathername");
				StringBuffer temp = new StringBuffer();
				if (weathername != null) {
					for (int i = 0; i < weathername.length; i++) {
						temp.append(weathername[i] + "#");
					}
				}
				menu.setNames(temp.toString());

				if (menu.getId() == null || menu.getId().equals("")) {
					menu.setCreator(current_user_id);
					menu.setCreateTime(new Date());
					menuManager.save(menu);
				} else {
					menuManager.update(menu);
				}

			} else if (type != null && type.equals("safe")) {

				// 安全天数保存
				Menu menu1 = new Menu();
				menu1.setId(this.getRequest().getParameter("safeId1"));
				menu1.setNames(this.getRequest().getParameter("safeName1"));
				menu1.setCreateTime(StaticMethod.dateString2Date(this
						.getRequest().getParameter("safe1")));
				menu1.setLocations("safe1");
				if (menu1.getId() == null || menu1.getId().equals("")) {
					menu1.setCreator(current_user_id);
					menuManager.save(menu1);
				} else {
					menuManager.update(menu1);
				}

				Menu menu2 = new Menu();
				menu2.setId(this.getRequest().getParameter("safeId2"));
				menu2.setNames(this.getRequest().getParameter("safeName2"));
				menu2.setCreateTime(StaticMethod.dateString2Date(this
						.getRequest().getParameter("safe2")));
				menu2.setLocations("safe2");
				if (menu2.getId() == null || menu2.getId().equals("")) {
					menu2.setCreator(current_user_id);
					menuManager.save(menu2);
				} else {
					menuManager.update(menu2);
				}

				Menu menu3 = new Menu();
				menu3.setId(this.getRequest().getParameter("safeId3"));
				menu3.setNames(this.getRequest().getParameter("safeName3"));
				menu3.setCreateTime(StaticMethod.dateString2Date(this
						.getRequest().getParameter("safe3")));
				menu3.setLocations("safe3");
				if (menu3.getId() == null || menu3.getId().equals("")) {
					menu3.setCreator(current_user_id);
					menuManager.save(menu3);
				} else {
					menuManager.update(menu3);
				}
			}
			if (type != null && type.equals("title")) {

				// 警句格言保存
				menu.setLocations("title");
				menu.setId(getRequest().getParameter("titleid"));
				menu.setNames(getRequest().getParameter("titlenames"));
				if (menu.getId() == null || menu.getId().equals("")) {
					menu.setCreator(current_user_id);
					menu.setCreateTime(new Date());
					menuManager.save(menu);
				} else {
					menuManager.update(menu);
				}

			} else {

				// 其他菜单保存
				if (menu.getId() == null || menu.getId().equals("")) {
					menu.setCreator(current_user_id);
					menu.setCreateTime(new Date());
					menuManager.save(menu);
				} else {
					menuManager.update(menu);
				}
			}
			result = "true";
		} catch (Exception e) {
			System.out.print(e);
		}
		// }
		return writeAjaxResponse(result);
	}

	/** 进入更新页面 */
	public String edit() {
		return EDIT_JSP;
	}

	/** 保存更新对象 */
	public String update() {
		String current_user_id = (String) this.getRequest().getSession()
				.getAttribute("userId");
		String result = "false";

		if (current_user_id != null && !current_user_id.equals("")) {
			try {
				menuManager.update(this.menu);
			} catch (Exception e) {
				System.out.print(e);
			}
		}
		return LIST_ACTION;
	}

	/** 删除对象 */
	public String deleteAjax() {
		String current_user_id = (String) this.getRequest().getSession()
				.getAttribute("userId");
		String result = "false";
		// if (current_user_id != null && !current_user_id.equals("")) {
		// 单个删除
		if (menu.getId() != null && !menu.getId().equals("")) {
			try {
				menuManager.removeById(menu.getId());
				result = "true";
			} catch (Exception e) {
				System.out.print(e);
			}
		}
		// }
		return writeAjaxResponse(result);
	}

	/** 删除对象 */
	public String delete() {
		String current_user_id = (String) this.getRequest().getSession()
				.getAttribute("userId");
		// if (current_user_id != null && !current_user_id.equals("")) {
		// 单个删除
		if (menu.getId() != null && !menu.getId().equals("")) {
			menuManager.removeById(menu.getId());
		}
		// 批量删除
		if (items != null) {
			for (String ids : items) {
				String[] idArray = ids.split(",");
				for (String id : idArray)
					menuManager.removeById(id);
			}
		}

		// }
		return LIST_ACTION;
	}

}
